from django.core.files.uploadedfile import UploadedFile
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

from annoying.decorators import render_to

from core.models import Link
from core.forms import SimpleUpload
from django.views.decorators.csrf import csrf_protect

validate = URLValidator(verify_exists = False)

def handle_uploaded_file(file = object):
    temp_file = '/tmp/%s' % file.name

    destination = open(temp_file, 'wb+')

    for chunk in file.chunks():
        destination.write(chunk)
    destination.close()

    link = open(temp_file, 'r')

    links_save_log = []

    for link_csv in link.readlines():
        (title, uri, screenshot, dump) = link_csv.split(',')

        try:
            validate(uri)
            try:
                Link.objects.get(link = uri)
                links_save_log.append({'status': 'warning', 'message': '%s already exists.' % uri})
            except Link.DoesNotExist:
                new_link = Link(title = title,
                                link = uri,
                                screenshot = int(screenshot),
                                dump = int(dump),
                                fullcheck = False)
                new_link.save()

                links_save_log.append({'status': 'ok', 'message': '%s successfully saved.' % uri})
        except ValidationError, ve:
            links_save_log.append({'status': 'ok', 'message': '%s is not a valid link.' % uri})

    link.close()

    return {'save_log': links_save_log}

@csrf_protect
@render_to('info.html')
def up(request):
    if request.POST:
        ufile = request.FILES['file']
        meta = UploadedFile(ufile)
        meta.read()

        ext = ufile.name.split('.')[-1:][0]

        if ext in ['txt', 'text', 'csv']:
            return handle_uploaded_file(file = ufile)
        else:
            return {'error': 'Wrong file type <a href="/link">Return</a>'}
    else:
        return {
            'action': '/up',
            'method': 'post',
            'name': 'test upload',
            'form': SimpleUpload().as_p()
        }